package com.stylefeng.guns.core.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

/**
 * 阿里云存储
 */
public class OSSUtil {

    // TODO 更户客户的正式阿里云存储信息
    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static final String accessKeyId = "LTAIYR7xB4GoddAU";
    private static final String accessKeySecret = "jJ1RbDnY7181vjP7pNJ411GOvaQ8Gw";
    private static final String bucket = "pro-bali";

    /**
     * 单文件字节上传，返回文件名，文件流获取请通过文件名由OSSClient生成{
     * @link OSSUtil#getFileUrl(String, int)}
     * @param bytes
     * @param originalFileName
     * @return
     */
    public static String putSingleFile(byte[] bytes, String originalFileName) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 生成唯一文件名
        String newFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")
                + "_" + originalFileName;
        // 上传
        ossClient.putObject(bucket, newFileName, new ByteArrayInputStream(bytes));
        // 关闭client
        ossClient.shutdown();

        return newFileName;
    }

    /**
     * 根据文件名获取文件访问URL
     * @param fileName 文件名
     * @param expires URL有效时间（小时）
     * @return
     */
    public static String getFileUrl(String fileName, int expires) {
        String path = "";
        /**
         * 当传入空字符串时，会返回所有的文件;故做如下校验；
         * 2017-12-26 15:45:21
         * Yan
         */
        if(StringUtils.isBlank(fileName)){
            return path;
        }
        // 创建OSSClient实例
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = client.generatePresignedUrl(bucket, fileName, DateUtils.dateAfter(new Date(), expires, Calendar.HOUR));
        try {
            url.getContent();// 如果文件不存在抛异常不给path设值
            path = url.toString();
        } catch (IOException e) {
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(30000);
                conn.setRequestMethod("GET");
                InputStream input;
                if (conn.getResponseCode() == 200) {
                    input = conn.getInputStream();
                } else {
                    input = conn.getErrorStream();
                }
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = input.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                byte[] data = outStream.toByteArray();
                outStream.close();
                input.close();
                System.out.println("获取文件" + fileName + "返回错误内容：");
                System.out.println(new String(data, "UTF-8"));
            } catch (IOException e1) {
                // 无需处理
            }
        }
        return path;
    }
    public static InputStream downloadFile(String ossKey)
    {
        OSSClient ossClient;
        OSSObject ossObject=null;
        try {
            String fileName = ossKey;
            // 创建OSSClient实例
            ossClient= new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 从阿里云进行下载
            ossObject= ossClient.getObject(bucket, ossKey);//bucketName需要自己设置
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return ossObject.getObjectContent();
    }

    public static void main(String[] args) throws IOException {
//        System.out.println(getFileUrl("20171115174649206_3182500884_1842381376.jpg", 1));
    }
}
